﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ServiceKit.Audit;
using System.Collections.Generic;
using System.Diagnostics;

namespace ServiceKit.WebApi
{
    public class AuditFilterData
    {
        private const string AbpAuditFilterDataHttpContextKey = "__AuditFilterData";

        public Stopwatch Stopwatch { get; }

        public AuditInfo AuditInfo { get; }

        public AuditFilterData(
            Stopwatch stopwatch,
            AuditInfo auditInfo)
        {
            Stopwatch = stopwatch;
            AuditInfo = auditInfo;
        }

        public static void Set(ActionExecutingContext actionContext, AuditFilterData auditFilterData)
        {
            GetAuditDataStack(actionContext.HttpContext).Push(auditFilterData);
        }
        
        public static AuditFilterData GetOrNull(ActionExecutedContext actionContext)
        {
            var stack = GetAuditDataStack(actionContext.HttpContext);
            return stack.Count <= 0
                ? null
                : stack.Pop();
        }

        public static AuditFilterData GetOrNull(Controller context)
        {
            var stack = GetAuditDataStack(context.HttpContext);
            return stack.Count <= 0
                ? null
                : stack.Pop();
        }


        private static Stack<AuditFilterData> GetAuditDataStack(HttpContext context)
        {
            if (!context.Items.ContainsKey(AbpAuditFilterDataHttpContextKey))
            {
                var stack = new Stack<AuditFilterData>();
                context.Items[AbpAuditFilterDataHttpContextKey] = stack;
                return stack;
            }
            else
            {
                return context.Items[AbpAuditFilterDataHttpContextKey] as Stack<AuditFilterData>;
            }
        }
    }
}
